package com.security.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    protected void configGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService);
//        auth.inMemoryAuthentication().withUser("admin").password("admin123").roles("USER");
    }
    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception{
        //  antMatchers 指定地址(可以指定多个地址用','隔开) permitAll 表示所有人都可以访问
        httpSecurity.authorizeRequests().antMatchers("css/**","/index","/index/**","api/login").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/customer/**","money/**").hasAnyRole("USER,ADMIN")
                .and()
// loginPage() 登录页的地址  failureUrl:登录失败或是未登录地址    loginProcessingUrl：登录post请求时候的地址
                .formLogin().loginPage("/login").failureUrl("/login-error")
                .and()
//  accessDeniedPage 当用户没有权限时候的地址
                .exceptionHandling().accessDeniedPage("/401");
        //  logoutSuccessUrl 用户退出成功时候的地址
        httpSecurity.logout().logoutSuccessUrl("/");
        //  csrf().disable() csrf功能未开启
        httpSecurity.csrf().disable();
    }
}
